<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\Area;
use app\common\tool\Result;
use think\facade\View;
use think\exception\ValidateException;
use app\common\model\Address as AddressModel;
use think\response\Json;

class Address extends Base
{
    /**
     * 获取地址列表
     */
    public function getList()
    {
        try {
            $map = ['uid' => $this->user->id];
            $list = AddressModel::getList($map, false, 'create_time', ['p', 'c', 'd']);
            return Result::success('获取成功！',$list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 修改地址添加
     */
    public function save(): Json
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'Address');
            return Result::fastReturn(AddressModel::add($param, $this->user));
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 地址详情
     */
    public function details($id)
    {
        try{
            $info = AddressModel::where(['id' =>$id , 'uid' => $this->user->id])
            ->with(['p', 'c', 'd'])->find();
            if (empty($info)) return Result::fail('地址不存在');
            return Result::success('获取成功！',$info);
        }catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 收货地址删除/设置默认地址
     */
    public function edit(): Json
    {
        $param =$this->request->post();
        try {
            return Result::fastReturn(AddressModel::edit($param, $this->user));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }

    }
    /**
     * 获取省市区
     */
    public function getArea($id, $level = 0)
    {
        return Result::success('获取成功！',Area::getArea($id ?: 0, $level));
    }
}
